//
//  XZNotificationList.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/22.
//  Copyright © 2018年 星道三好. All rights reserved.
//

#import "XZNotificationList.h"
#import "XZNotificationCell.h"
#import "XZSelectStudentVC.h"
#import "XZNoticeDetailVC.h"

@interface XZNotificationList ()<UITableViewDelegate, UITableViewDataSource>

/** 表单 */
@property (nonatomic, strong) UITableView *tableView;
/** 数据存放地 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/** 当前的页 */
@property (nonatomic, assign) NSInteger CurrentPage;
/** 临时保存的页数 */
@property (nonatomic, assign) NSInteger TempPage;

@end

@implementation XZNotificationList

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"机构通告";
 
    // 配置tableView
    [self ConfigtableView];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(leftBarButtonItemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
}



-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}]; //设置标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    
    [SVProgressHUD dismiss];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];//设置标题颜色
}

- (void)leftBarButtonItemAction{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Config
/** 配置tableView */
- (void)ConfigtableView {
    
    self.view.backgroundColor = ColorRGB(245, 245, 245);
    // 设置代理
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //取消分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 设置占位View
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    // 设置自动Cell高
    self.tableView.rowHeight = 100;
    // 设置预注册
    [self.tableView registerClass:[XZNotificationCell class] forCellReuseIdentifier:@"cell"];
    // 增加刷新头
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 每次下拉刷新时都保存好当前的页数，预防刷新失败后页数错乱
        self.TempPage = self.CurrentPage;
        // 当前的刷新设为1
        self.CurrentPage = 1;
        // 获取数据
        [self RefreshData];
    }];
    // 增加刷新尾
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 获取数据
        [self RefreshData];
    }];
    // 开始刷新
    [self.tableView.mj_header beginRefreshing];
}


#pragma mark - 网络
- (void)RefreshData {
    
    //http://192.168.0.226:8080/StarShine/ys/assignHomework.do?action=getOrganizationAnnunciate&pageNumber=1
    
    NSDictionary *Params = @{
                             @"action":@"getOrganizationAnnunciate",
                             @"pageNumber":@(self.CurrentPage)
                             };

    [NetManager Get:LLBaseURL(@"assignHomework.do") Auth:YES Params:Params Success:^(id Obj) {
        // 结束刷新
        [self MgrRefresh:1];
        // 数据处理
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            // 拿到数据
            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 如果当前的页码是1就先清空原数据
            self.CurrentPage == 1 ? [self.DataArr removeAllObjects] : nil;
            // 如果没有数据就提示没数据了
            if (Arr.count == 0) {
                [self MgrRefresh:2];
            } else {
                // 终于有数据啦
                [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 处理模型转对象
                    
                    XZNotificationModel *model = [[XZNotificationModel alloc] init_ValuForKeyWithDict:obj];
                    [self.DataArr addObject:model];
                }];
                self.CurrentPage += 1;
                [self MgrRefresh:3];
            }
        } else {
            // 数据获取失败
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
            [self MgrPage];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
        [self MgrRefresh:1];
        [self MgrPage];
    }];
}

/** 刷新失败时的页数处理 */
- (void)MgrPage {
    
    self.CurrentPage = self.TempPage;
}

/** 刷新状态 1结束刷新 2没有更多数据了 3刷新表单*/
- (void)MgrRefresh:(NSInteger)State {
    
    if (State == 1) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } else if (State == 2) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else if (State == 3) {
        [self.tableView reloadData];
    } else  {
        // 无
    }
}

#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XZNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.model = self.DataArr[indexPath.row];
    cell.CallBack = ^(NSString *ID) {
        XZNoticeDetailVC *vc = [XZNoticeDetailVC new];
        vc.ID = ID;
        [self.navigationController pushViewController:vc animated:YES];
    };
    return cell;
}


#pragma mark - 底部按钮点击事件
- (void)buttonTapped:(UIButton *)button {
    
    XZSelectStudentVC *VC = [XZSelectStudentVC new];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark - Get
- (NSMutableArray *)DataArr {
    if (!_DataArr) {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

- (UITableView *)tableView {
    if (!_tableView) {
        UIButton *bottomImage = [[UIButton alloc] init];
        [bottomImage setBackgroundImage:[UIImage imageNamed:@"btn_organization_pulish_default"] forState:(UIControlStateNormal)];
        [bottomImage setTitle:@"发通告" forState:(UIControlStateNormal)];
        [bottomImage setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [bottomImage addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
        bottomImage.adjustsImageWhenHighlighted = NO;
        [self.view addSubview:bottomImage];

        [bottomImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.offset(95*(SCREEN_WIDTH/375));
        }];
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
        _tableView.backgroundColor = ColorRGB(245, 245, 245);
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.bottom.equalTo(bottomImage.mas_top);
        }];
    }
    return _tableView;
}

@end
